package com.esh.oa.search

import android.app.DialogFragment
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.text.TextUtils
import android.view.*
import com.donkor.deepnight.utils.showToast
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.guoqi.keepsign.IPConfig
import com.guoqi.keepsign.R
import com.guoqi.keepsign.ligui.LiguiUI
import com.guoqi.keepsign.mzt.MztZtUI
import com.guoqi.keepsign.search.CircularRevealAnim
import com.guoqi.keepsign.search.SearchAdapter
import com.guoqi.keepsign.utils.KeyBoardUtils
import kotlinx.android.synthetic.main.view_search_page.*

/**
 * Created by GUOQI on 2017/12/21.
 */
const val SEARCH_TAG = "SearchFragment"

class SearchFragment : DialogFragment(), CircularRevealAnim.AnimListener,
        ViewTreeObserver.OnPreDrawListener, DialogInterface.OnKeyListener,
        View.OnClickListener {
    var data: MutableList<String> = arrayListOf("制服诱惑", "黑丝", "爱尤物", "情趣内衣", "人妻熟女", "前凸后翘", "蜜桃社", "空姐", "清纯甜美", "丽柜")
    lateinit var mRootView: View
    lateinit var mCircularRevealAnim: CircularRevealAnim
    lateinit var mAdatper: SearchAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.searchDialogStyle);

    }

    override fun onStart() {
        super.onStart()
        initDialog()
    }

    private fun initDialog() {
        val window = dialog.window
        val metrics = resources.displayMetrics
        val width = (metrics.widthPixels * 0.98).toInt() //DialogSearch的宽
        window!!.setLayout(width, WindowManager.LayoutParams.MATCH_PARENT)
        window.setGravity(Gravity.TOP)
        window.setWindowAnimations(R.style.searchDialogEmptyAnimation)//取消过渡动画 , 使DialogSearch的出现更加平滑
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mRootView = inflater?.inflate(R.layout.view_search_page, container, false)!!

        return mRootView
    }


    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
        setData()
    }


    private fun setData() {
        mAdatper = SearchAdapter(activity, data as ArrayList<String>)
        mAdatper.setOnDialogDismissListener(object : SearchAdapter.OnDialogDismiss {
            override fun onDismiss(keyWord: String) {
                hideAnim()
                if (keyWord == "丽柜") {
                    startActivity(Intent(activity, LiguiUI::class.java))
                } else {
                    goSearch(keyWord)
                }
            }
        })
        val manager = FlexboxLayoutManager()
        //设置主轴排列方式
        manager.flexDirection = FlexDirection.ROW
        //设置是否换行
        manager.flexWrap = FlexWrap.WRAP
        recyclerView.layoutManager = manager
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.adapter = mAdatper
    }

    private fun init() {
        mCircularRevealAnim = CircularRevealAnim()
        mCircularRevealAnim.setAnimListener(this)
        dialog.setOnKeyListener(this)
        iv_search_search.viewTreeObserver.addOnPreDrawListener(this)
        iv_search_search.setOnClickListener(this)
        iv_search_back.setOnClickListener(this)
    }

    override fun onHideAnimationEnd() {
        et_search_keyword.setText("");
        dismiss();
    }

    override fun onShowAnimationEnd() {
        if (isVisible) {
            KeyBoardUtils.openKeyboard(activity, et_search_keyword);
        }
    }

    override fun onPreDraw(): Boolean {
        iv_search_search.viewTreeObserver.removeOnPreDrawListener(this);
        mCircularRevealAnim.show(iv_search_search, mRootView);
        return true;
    }

    override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_UP) {
            hideAnim()
        } else if (keyCode == KeyEvent.KEYCODE_ENTER && event?.action == KeyEvent.ACTION_DOWN) {
            search()
        }
        return false
    }

    private fun search() {
        val searchKey = et_search_keyword.text.toString()
        if (TextUtils.isEmpty(searchKey.trim { it <= ' ' })) {
            activity?.showToast("请输入关键字")
        } else {
            hideAnim()
            goSearch(searchKey)
        }
    }

    private fun goSearch(keyWord: String) {
        val intent = Intent(activity, MztZtUI::class.java)
        intent.putExtra("keyWord", keyWord)
        intent.putExtra("url", IPConfig.MZT + "/search/" + keyWord + "/page/")
        activity.startActivity(intent)
    }

    private fun hideAnim() {
        KeyBoardUtils.closeKeyboard(activity, et_search_keyword);
        mCircularRevealAnim.hide(iv_search_search, mRootView)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_search_back -> {
                hideAnim()
            }
            R.id.iv_search_search -> {
                search()
            }
        }
    }

}